package com.atguigu.gmall.realtime.utils;

import org.apache.flink.api.common.serialization.DeserializationSchema;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;

import java.io.IOException;

/**
 * @author Felix
 * @date 2023/7/4
 * 操作kafka的工具类
 */
public class KafkaUtil {
    private static final String KAFKA_SERVER = "hadoop102:9092,hadoop103:9092,hadoop104:9092";

    //获取kafkaSource
    public static KafkaSource<String> getKafkaSource(String topic, String groupId) {
        KafkaSource<String> kafkaSource = KafkaSource.<String>builder()
            .setBootstrapServers(KAFKA_SERVER)
            .setTopics(topic)
            .setGroupId(groupId)
            //在生产环境，为了保证消费的一致性，应该读取已提交数据
            // .setProperty(ConsumerConfig.ISOLATION_LEVEL_CONFIG,"read_committed")
            // 从消费组提交的位点开始消费，如果提交位点不存在，使用最新位点；生产环境推荐使用这种方式
            // .setStartingOffsets(OffsetsInitializer.committedOffsets(OffsetResetStrategy.LATEST))
            .setStartingOffsets(OffsetsInitializer.latest())
            //注意：如果使用SimpleStringSchema对读取的数据进行反序列化，如果从kafka中读取的消息是空的话，处理不了
            // .setValueOnlyDeserializer(new SimpleStringSchema())
            .setValueOnlyDeserializer(new DeserializationSchema<String>() {
                @Override
                public String deserialize(byte[] message) throws IOException {
                    if (message != null) {
                        return new String(message);
                    }
                    return null;
                }

                @Override
                public boolean isEndOfStream(String nextElement) {
                    return false;
                }

                @Override
                public TypeInformation<String> getProducedType() {
                    return TypeInformation.of(String.class);
                }
            })
            .build();
        return kafkaSource;
    }

    //获取kafkaSink
    public static KafkaSink<String> getKafkaSink(String topic) {
        KafkaSink<String> kafkaSink = KafkaSink.<String>builder()
            .setBootstrapServers(KAFKA_SERVER)
            .setRecordSerializer(KafkaRecordSerializationSchema.builder()
                .setTopic(topic)
                .setValueSerializationSchema(new SimpleStringSchema())
                .build()
            )
            //1.要想保证写入的一致性，需要将DeliveryGuarantee.EXACTLY_ONCE，底层才会开启事务，进行两阶段提交
            //2.要向保证写入的一致性，检查必须要开启
            //3.要向保证写入的一致性，开启检查点之后，事务的超时时间必须大于检查点超时时间，并小于最大的超时时间
            //4.要向保证写入的一致性，需要设置事务的前缀
            //5.要向保证写入的一致性，在消费者端，需要设置隔离级别为ConsumerConfig.ISOLATION_LEVEL_CONFIG为read_committed
            // .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
            // .setTransactionalIdPrefix("dwd_traffic_log_split")
            // .setProperty(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG,15*60*1000+"")
            .build();
        return kafkaSink;
    }

    //获取从topic_db主题中读取数据创建动态表的建表语句
    public static String getTopicDbDDL(String groupId) {
        return "CREATE TABLE topic_db (\n" +
            "  `database` string,\n" +
            "  `table` string,\n" +
            "  `type` string,\n" +
            "  `ts` string,\n" +
            "  `data` map<string,string>,\n" +
            "  `old` map<string,string>,\n" +
            "  proc_time as PROCTIME()\n" +
            ")" + getKafkaDDL("topic_db", groupId);
    }

    //获取kafak连接器连接属性
    public static String getKafkaDDL(String topic, String groupId) {
        return "WITH (\n" +
            "  'connector' = 'kafka',\n" +
            "  'topic' = '" + topic + "',\n" +
            "  'properties.bootstrap.servers' = '" + KAFKA_SERVER + "',\n" +
            "  'properties.group.id' = '" + groupId + "',\n" +
            "  'scan.startup.mode' = 'latest-offset',\n" +
            "  'format' = 'json'\n" +
            ")";
    }

    //获取upsert-kafka连接器连接属性
    public static String getUpsertKafkaDDL(String topic) {
        return "WITH (\n" +
            "  'connector' = 'upsert-kafka',\n" +
            "  'topic' = '" + topic + "',\n" +
            "  'properties.bootstrap.servers' = '" + KAFKA_SERVER + "',\n" +
            "  'key.format' = 'json',\n" +
            "  'value.format' = 'json'\n" +
            ")";
    }

    //获取KafkaSink
    public static <T>KafkaSink<T> getKafkaSinkBySchema(KafkaRecordSerializationSchema<T> kafkaRecordSerializationSchema) {
        KafkaSink<T> kafkaSink = KafkaSink.<T>builder()
            .setBootstrapServers(KAFKA_SERVER)
            .setRecordSerializer(
                kafkaRecordSerializationSchema
            )
            .build();
        return kafkaSink;
    }
}
